<template>
  <a-row justify="center" align="middle" style="height: 100vh; background-color: #f0f2f5">
    <a-col>
      <a-card class="login-card" justify-center="justify-center">
        <h2 style="text-align: center; margin-bottom: 20px;color: #555">简图-用户登录</h2>
        <a-form layout="vertical" :model="form" :rules="rules" @finish="onSubmit" autocomplete="off" >
          <!-- 用户名 -->
          <a-form-item name="username" required>
            <a-input v-model:value="form.username" placeholder="请输入用户名" />
          </a-form-item>

          <!-- 密码 -->
          <a-form-item name="password" required>
            <a-input-password v-model:value="form.password" placeholder="请输入密码" />
          </a-form-item>

          <!-- 记住我 -->
          <a-form-item style="text-align: right;padding-right: 28px">
            <a-checkbox v-model:checked="form.remember" style="color: #777">记住我</a-checkbox>
          </a-form-item>

          <!-- 登录按钮 -->
          <a-form-item>
            <a-button type="primary" block htmlType="submit">登录</a-button>
          </a-form-item>
        </a-form>

        <!-- 注册链接 -->
        <div style="text-align: center">
          <a-space>
            <span style="color: #bbb">还没有账号？</span>
            <a @click="goToRegister">立即注册</a>
          </a-space>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { message } from 'ant-design-vue'
import { userStore } from '@/stores/user.ts'

// 表单数据
const form = reactive({
  username: '',
  password: '',
  remember: false,
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少3个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' },
  ],
}

// 获取URL中的查询参数
const urlParams = new URLSearchParams(window.location.search)
const redirectUrl = urlParams.get('redirect') // 获取 redirect 参数

// 登录提交事件
const onSubmit = () => {
  userStore()
    .userLogin(form.username, form.password)
    .then(() => {
      message.success('登录成功')
      if (!redirectUrl) {
        window.location.href = '/'
      } else {
        window.location.href = redirectUrl
      }
    })
}

// 跳转到注册页面
const goToRegister = () => {
  window.location.href = '/user/register' // 根据实际路由修改路径
}
</script>

<style scoped>
.login-card {
  min-width: 400px;
}
</style>
